using System.Linq;
using MallSystembackend.Api.Model;
using MallSystembackend.Api.ParamModel;
using MallSystembackend.Api.Repository;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;

namespace MallSystembackend.Api.Controllers
{
    //订单路由
    public class OrderFormControllers : ControllerBase
    {
        public IRepository<OrderForm> _orderFormRepository;

        public IRepository<Merchant> _merchantRepository;

        public IRepository<Commodity> _commodityRepository;

        public OrderFormControllers(
            IRepository<OrderForm> orderFormRepository,
            IRepository<Merchant> merchantRepository
        )
        {
            _orderFormRepository = orderFormRepository;
            _merchantRepository = merchantRepository;
        }

        //根据店主id获取他的所有订单
        [HttpGet("{id}")]
        public ActionResult GetAllOrderFormByid(int id)
        {
            var orderForms = _orderFormRepository.Table.ToList();

            var merchantById =
                _merchantRepository.Table.Where(x => x.UsersId == id).ToList();

            var commoditys = _commodityRepository.Table.ToList();

            //获取店铺所有商品
            var commidity =
                (
                from commodity in commoditys
                join merchant
                in merchantById
                on commodity.MerchantId
                equals merchant.Id
                select commodity
                ).ToList();

            var orderForm =
                (
                from orderform in orderForms
                join commidityId
                in commidity
                on orderform.CommodityId
                equals commidityId.Id
                select orderform
                ).ToList();

            return Ok(new {
                Code = 1000,
                Data = orderForms,
                Msg = "获取成功"
            });
        }

        //根据客户id获取他的所有订单
        [HttpGet("user/{id}")]
        public ActionResult GetAllOrderFormByCustomerid(int id)
        {
            var orderFrom = _orderFormRepository.Table.Where(x => x.UsersId ==id).ToList();

            return Ok(new {
                Code = 1000,
                Data = orderFrom,
                Msg = "获取用户订单成功"
            });
        }

        //添加订单
        [HttpPost]
        public ActionResult AddOrderForm(ParamOrderForm model)
        {
            var orderform = new OrderForm {
                CommodityId = model.CommodityId,
                UsersId = model.UsersId,
                ShipAddressId = model.UsersId,
                CustomerAddressId = model.CommodityId
            };

            _orderFormRepository.Insert(orderform);

            return Ok(new{
                Code = 1000,
                Data = orderform,
                Msg = "添加成功"
            });
        }
    }
}
